package com.ficus.road.maintain.core.infrastructure.mongo.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bson.types.ObjectId;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class ConvertUtility {

    public static ObjectId toObjectId(String id) {
        return new ObjectId(id);
    }

    public static Collection<ObjectId> toObjectIdList(Collection<String> ids) {
        return ids.stream()
                .map(ObjectId::new)
                .collect(Collectors.toList());
    }

    public static Collection<Integer> toInteger(Collection<IntEnum> enums) {
        return enums.stream()
                .map(IntEnum::getCode)
                .collect(Collectors.toList());
    }

    public static Map<String, Object> toMap(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        TypeReference<HashMap<String, Object>> typeRef
                = new TypeReference<HashMap<String, Object>>() {
        };

        try {
            return mapper.readValue(jsonString, typeRef);
        } catch (IOException exception) {
            exception.printStackTrace();
            return new HashMap<String, Object>();
        }
    }

    public static String toJsonString(Map<String, Object> map) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(map);
        } catch (JsonProcessingException exception) {
            exception.printStackTrace();
            throw exception;
        }
    }
}
